package com.hsgene.user.service.impl;

import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.security.MD5Utils;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.user.persistence.ManagerRepository;
import com.hsgene.user.persistence.UserRepository;
import com.hsgene.user.service.PasswordService;
import com.hsgene.user.service.api.SecurityService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 密码管理ServiceImpl
 *
 * @author wangbing
 * @version 1.0, 2018/7/31
 */
@Service
public class PasswordServiceImpl implements PasswordService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private ManagerRepository managerRepository;

    @Resource
    private SecurityService securityService;

    @Override
    public ApiResult<NullObject> updatePassword(List<String> userIds, String password, boolean decrypted) {
        FieldChecker.checkEmpty(userIds, "userIds");
        if (!decrypted) {
            ApiResult<String> decryptResult = securityService.rsaDecrypt(password);
            if (!decryptResult.isSucc()) {
                return ApiResult.fail(decryptResult.getError());
            }
            password = decryptResult.getData();
        }
        userRepository.updatePassword(userIds, MD5Utils.getMD5Code(password));
        managerRepository.updatePassword(userIds, MD5Utils.getMD5Code(password));

        return ApiResult.succ();
    }

    @Override
    public ApiResult<NullObject> updateSupplierSuperPassword(Long supplierId, String password, boolean decrypted) {
        FieldChecker.checkEmpty(supplierId, "supplierId");
        if (!decrypted) {
            ApiResult<String> decryptResult = securityService.rsaDecrypt(password);
            if (!decryptResult.isSucc()) {
                return ApiResult.fail(decryptResult.getError());
            }
            password = decryptResult.getData();
        }

        managerRepository.updateSupplierPassword(supplierId, MD5Utils.getMD5Code(password));

        return ApiResult.succ();
    }
}
